import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/Dashboard.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/users',
    name: 'Users',
    component: () => import('@/views/UserManagement.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/Profile.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/personal-accounting',
    name: 'PersonalAccounting',
    component: () => import('@/views/PersonalAccounting.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/personal-affairs',
    name: 'PersonalAffairs',
    component: () => import('@/views/PersonalAffairs.vue'),
    meta: { requiresAuth: true }
  },
  // 新增：事务库管理
  {
    path: '/affair-catalog',
    name: 'AffairCatalog',
    component: () => import('@/views/AffairCatalog.vue'),
    meta: { requiresAuth: true }
  },
  // 新增：实验报告上传与提交情况
  {
    path: '/lab-report/upload',
    name: 'LabReportUpload',
    component: () => import('@/views/LabReportUpload.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/lab-report/status',
    name: 'LabReportStatus',
    component: () => import('@/views/LabReportStatus.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/major-report/upload',
    name: 'MajorReportUpload',
    component: () => import('@/views/MajorReportUpload.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/major-report/status',
    name: 'MajorReportStatus',
    component: () => import('@/views/MajorReportStatus.vue'),
    meta: { requiresAuth: true }
  },
  // 新增：学习记录新增与总览
  {
    path: '/learning-record/create',
    name: 'LearningRecordCreate',
    component: () => import('@/views/LearningRecordCreate.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/learning-record/overview',
    name: 'LearningRecordOverview',
    component: () => import('@/views/LearningRecordOverview.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const isLoggedIn = store.getters.isLoggedIn
  
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login')
  } else if (to.path === '/login' && isLoggedIn) {
    next('/dashboard')
  } else {
    next()
  }
})

export default router
